<template>
  <div class="ucenter-content">
    <div class="title">{{ name }}</div>
    <div class="chart">
      <div class="m1">
        <ChartCard :title="'系统信息'" :link="'111'">
          <template #rightDiv>
            <el-button type="primary" link @click="openUcenter" style="margin-top: 4px">点击进入&nbsp;&nbsp;>></el-button>
          </template>
          <template #chart>
            <div class="c1">
              <img src="../img/logo.png" />
              <el-descriptions :column="1">
                <el-descriptions-item label="对接状态">
                  <el-tag v-if="isNormal" size="small">正常</el-tag>
                  <el-tag v-else type="danger" size="small" @click="openMonitor" style="cursor: pointer">异常</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="系统名称">Ucenter</el-descriptions-item>
                <el-descriptions-item label="所属厂商">H3C</el-descriptions-item>
                <el-descriptions-item label="系统版本">V1.1.0</el-descriptions-item>
                <el-descriptions-item label="所属网域">
                  <el-select ref="type" v-model="systemInfo.netWork" placeholder="请选择" style="width: 60%">
                    <el-option :value="'运维管理网'" :label="'运维管理网'"></el-option>
                  </el-select>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </ChartCard>
      </div>
      <div class="m2">
        <ChartCard :title="'系统监控态势'">
          <template #chart>
            <div class="chart c2">
              <SystemLine :name="'分值'" :data="sysScoreData"></SystemLine>
            </div>
          </template>
        </ChartCard>
      </div>
    </div>
    <ChartCard :title="'告警总览'">
      <template #chart>
        <div class="chart c3">
          <AlarmNumCard></AlarmNumCard>
          <div class="c3-2">
            <div class="c3-2-m1">
              <MiniChartCard :title="'告警趋势'">
                <template #chart>
                  <AlarmTrend :type="alarmType" :data="alarmTrendData"></AlarmTrend>
                </template>
              </MiniChartCard>
            </div>
            <div class="c3-2-m2">
              <MiniChartCard :title="'24h待处置告警'">
                <template #chart>
                  <PieEcharts :name="'告警'" :data="alarm24EchartsData" :color-list="alarm24EchartsColor"></PieEcharts>
                </template>
              </MiniChartCard>
            </div>
            <div class="c3-2-m3">
              <MiniChartCard :title="'全量告警（3年）'">
                <template #chart>
                  <PieEcharts :name="'告警'" :data="alarmHisEchartsData" :color-list="alarmHisEchartsColor"></PieEcharts>
                </template>
              </MiniChartCard>
            </div>
          </div>
        </div>
      </template>
    </ChartCard>
  </div>
</template>

<script setup lang="ts" name="System">
import { onMounted, ref, reactive, computed, onBeforeUnmount } from "vue";
import ChartCard from "../component/chartCard.vue";
import MiniChartCard from "../component/minChartCard.vue";
import SystemLine from "../component/lineEcharts.vue";
import AlarmTrend from "../component/barEcharts.vue";
import PieEcharts from "../component/pieEcharts.vue";
import AlarmNumCard from "./alarmNumCard.vue";
import { getAlarmEchartsApi } from "@/api/modules/netManagement/ucenter";
import { getImportance } from "@/api/modules/warning/warning24Hours";
import { getAppConditionList } from "@/api/modules/monitorManagement/OMManagement";
// import html2canvas from "html2canvas";
import { useRouter } from "vue-router";
import moment from "moment";

const router = useRouter();
export interface Props {
  name: string;
}
withDefaults(defineProps<Props>(), {
  name: ""
});
const systemInfo = ref({
  netWork: "运维管理网"
});
const isNormal = ref(false);
const alarmType = reactive([
  { name: "紧急", key: "critical", color: "#F6302FFF" },
  { name: "重要", key: "major", color: "#FF8F1FFF" },
  { name: "次要", key: "minor", color: "#FFE65DFF" },
  { name: "警告", key: "info", color: "#1F8CF2FF" },
  { name: "通知", key: "event", color: "#29D3DAFF" }
]);
const alarmTrendData = ref({});
const alarmHisData = ref({});
// 全量告警
const alarmHisEchartsData = ref([]);
const alarmHisEchartsColor = computed(() => alarmType.map(a => a.color));

const sysScoreData = ref([
  { name: "11月1号", value: 80 },
  { name: "11月2号", value: 81 },
  { name: "11月3号", value: 72 },
  { name: "11月4号", value: 80 },
  { name: "11月5号", value: 50 },
  { name: "11月6号", value: 80 }
]);
// 24h告警
const alarm24Type = reactive([
  { name: "重点关注", key: "important", color: "#F6302FFF" },
  { name: "一般关注", key: "common", color: "#FF8F1FFF" },
  { name: "未分类", key: "default", color: "#D8E0F0FF" }
]);
const alarm24EchartsData = ref([]);
const alarm24EchartsColor = computed(() => alarm24Type.map(a => a.color));

// const convertToBase64 = async id => {
//   if (!id) return;
//   const html: any = document.getElementById(id);
//   let baseImg;
//   if (html) {
//     await html2canvas(html).then(async canvas => {
//       baseImg = canvas.toDataURL("png");
//     });
//     return baseImg;
//   }
// };

// const getEchartsBase64 = async () => {
//   const baseUrl = await convertToBase64("testImg");
//   console.log(baseUrl);
// };

const checkSysStatus = () => {
  isNormal.value = false;
  const params = {
    system_name: "ucenter",
    page: 1,
    page_size: 10
  };
  getAppConditionList(params)
    .then(res => {
      const data: any = res.data!["results"] || [];
      if (data.length && data[0].auth_api_available && data[0].data_api_available) {
        isNormal.value = true;
      }
    })
    .catch(error => {
      console.log(error);
    });
};

const openMonitor = () => {
  router.push({ path: "/operation_maintenance_monitor", query: { tab: "thrid" } });
};

const openUcenter = () => {
  window.open(`https://10.14.129.15:30000/central/index.html#/dashboardui/index.html#/out/show/bigscreen-front`, "_blank");
};

// 获取告警趋势
const getAlarmTrendData = async () => {
  const today = new Date();
  const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
  const params = {
    chartDataFlag: true,
    start: 1,
    size: 15,
    sort: "faultTimeReach",
    order: "DESC",
    containsInput: 0,
    filterJuheFlag: 0,
    startAlarmTime: moment(firstDay).format("YYYY-MM-DD 00:00"),
    endAlarmTime: moment(today).format("YYYY-MM-DD 23:59"),
    alarmType: "0",
    regionId: "",
    interfaceIndex: ""
  };
  await getAlarmEchartsApi(params)
    .then(res => {
      alarmTrendData.value = res.data || {};
    })
    .catch(error => {
      console.log(error);
      alarmTrendData.value = {};
    });
};
// 获取全量告警数据
const getAlarmHisData = async () => {
  const today = new Date();
  const firstDay = new Date(today.getFullYear() - 3, today.getMonth(), today.getDate());
  const params = {
    chartDataFlag: true,
    start: 1,
    size: 15,
    sort: "faultTimeReach",
    order: "DESC",
    containsInput: 0,
    filterJuheFlag: 0,
    startAlarmTime: moment(firstDay).format("YYYY-MM-DD 00:00"),
    endAlarmTime: moment(today).format("YYYY-MM-DD 23:59"),
    alarmType: "1",
    regionId: "",
    interfaceIndex: ""
  };
  await getAlarmEchartsApi(params)
    .then(res => {
      alarmHisData.value = res.data || {};
    })
    .catch(error => {
      console.log(error);
      alarmHisData.value = {};
    });
  getHisEchartsData();
};
// 计算全量echart图数据
const getHisEchartsData = () => {
  const list: any = [];
  alarmType.forEach(item => {
    const key = "total" + item.key.charAt(0).toUpperCase() + item.key.slice(1) + "New";
    list.push({
      name: item.name,
      value: alarmHisData.value[key] || 0
    });
  });
  alarmHisEchartsData.value = list;
};

const getAlarm24Data = async () => {
  const today = new Date();
  const after24 = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
  const params = {
    is_handled: false,
    system_type: "ucenterH3c",
    start_time: moment(today).format("YYYY-MM-DD HH:mm:ss"),
    end_time: moment(after24).format("YYYY-MM-DD HH:mm:ss")
  };
  const { data } = await getImportance(params);
  const list: any = [];
  alarm24Type.forEach(item => {
    const itemData = (data || []).find(a => a.importance_key === item.key);
    list.push({
      name: item.name,
      value: itemData ? itemData.count : 0
    });
  });
  alarm24EchartsData.value = list;
};

const getAllChartData = () => {
  checkSysStatus();
  getAlarmTrendData();
  getAlarmHisData();
  getAlarm24Data();
};
let refreshIntervalId: any = null;
onMounted(() => {
  getAllChartData();
  refreshIntervalId = setInterval(() => {
    getAllChartData();
  }, 10000);
});
onBeforeUnmount(() => {
  clearInterval(refreshIntervalId);
});
</script>

<style scoped lang="scss">
@import "../common.scss";
.ucenter-content {
  .m1 {
    flex: 1;
    min-width: 450px;
    height: 288px;
  }
  .m2 {
    flex: 2;
    min-width: 600px;
    height: 288px;
  }
  .c1 {
    display: grid;
    grid-template-columns: 50% 50%;
    align-items: center;
    height: 100%;
    img {
      width: 60%;
      height: 60%;
      min-height: 0;
      margin: 0 auto;
    }
    :deep() .el-descriptions__label:not(.is-bordered-label) {
      color: var(--el-header-menu-text-color);
    }
  }
  .c3 {
    flex-direction: column;
    .c3-1 {
      display: flex;
      flex-wrap: wrap;
      gap: 16px 16px;
    }
    .c3-2 {
      // flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      .c3-2-m1 {
        flex: 2;
        min-width: 700px;
        height: 320px;
      }
      .c3-2-m2 {
        flex: 1;
        min-width: 350px;
        height: 320px;
      }
      .c3-2-m3 {
        flex: 1;
        min-width: 350px;
        height: 320px;
      }
    }
  }
}
</style>
